package com.example.boot1;

import java.util.concurrent.*;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        //testJDKThreadPool()
        test手写ThreadPool();

    }


    public static void testJDKThreadPool(){

        //cpu核
        //System.out.println("cpu 核数: "+Runtime.getRuntime().availableProcessors());

        //场景：ExecutorService 银行 ，  5柜台个窗口  10个线程要办业务

        //ExecutorService threadPool = Executors.newFixedThreadPool(5);//固定5线程
        //ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池一个线程
        ExecutorService threadPool = Executors.newCachedThreadPool();//N个，根据处理能力 可扩容

        try {
            //模拟10个用户来办理业务，每个用户就是一个来自外部得请求线程
            for (int i = 1; i <=10 ; i++) {
                threadPool.execute(()-> {
                    System.out.println(Thread.currentThread().getName()+"\t 办理业务!");
                });
                //看某一些效果使用
                //try{ TimeUnit.SECONDS.sleep(1);} catch(Exception e){e.printStackTrace();}
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            threadPool.shutdown();
        }

    }

    public static void test手写ThreadPool(){

        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        try {
            //模拟10个用户来办理业务，每个用户就是一个来自外部得请求线程
            //当超过最大线程数+阻塞队列数时 会拒绝接收任务  通常这个策略是自己实现RejectedExecutionHandler
            for (int i = 1; i <=10 ; i++) {
                threadPool.execute(()-> {
                    System.out.println(Thread.currentThread().getName()+"\t 办理业务!");
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            threadPool.shutdown();
        }
    }
}
